package com.dubbo.bootstrap;


import com.dubbo.StaticConstants;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;

public class NettyServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
        String host = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();

        System.out.println("host: " + host);
        if ("127.0.0.1".equals(host) && StaticConstants.STOP_MARK.equals(request)) {
            ChannelFuture future = ctx.write("ok");
            future.addListener(ChannelFutureListener.CLOSE);
            ApplicationHolder.get().stop();
        } else {
            ChannelFuture future = ctx.write("error");
            future.addListener(ChannelFutureListener.CLOSE);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}
